﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using FastReport;
using FastReport.Export.Pdf;
using CronCommon;
using System.Data;
using System.Data.SqlClient;


namespace DN
{
    class Program
    {

        static void Main(string[] args)
        {
            //参数解析
            CmdParameter cmd = new CmdParameter(Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName), args);
            if (!cmd.CmdParameterCheck) return;

            Log.Writter("----------------------------------------------");

            try
            {

                SqlConnection conn = DbConn.GetDbConnection();
                if (conn == null)
                {
                    Log.Writter("数据连接失败");
                    return;
                }

                CronStruct cs = DbConn.GetCron(conn, args[0]);

                if (cs == null)
                {
                    Log.Writter("取得任务数据失败");
                    return;
                }

                DbConn.CronStateUpdae(conn, args[0]);

               //测试邮件设定
                cs.cmd = cmd;
                if (cmd.SendTestMail) cs.TestSendMailSet();

                if (!cmd.SendHistoryRecord)
                {
                    if (!DbConn.CheckAttachmentData(conn, args[0]))
                    {
                        Log.Writter("没有设定附件的存储过程");
                        return;
                    }


                    DataSet ds = DbConn.GetAttachmentData(conn, args[0]);
                    if (ds == null)
                    {
                        Log.Writter("没有附件数据集");
                        return;
                    }

                    Log.Writter(string.Format("附档数据表{0} 数据笔数 {1}", ds.Tables[0].TableName, ds.Tables[0].Rows.Count.ToString()));

                    bool isTableRecord = false;
                    for (int i = 0; i < ds.Tables.Count; i++)
                    {
                        if (ds.Tables[i].Rows.Count > 0) isTableRecord = true;
                    }

                    if (!isTableRecord)
                    {
                        Log.Writter(string.Format("有附档格式配置，但附件没有需要导出的数据，不发送邮件"));
                        return;
                    }

                    string templateFilename = $"{Dir.GetCurrentDirectory()}\\template\\{cs.附件文件名}.frx";


                    if (!File.Exists(templateFilename))
                    {

                        Log.Writter(string.Format("模板文件不存在 {0}", templateFilename));
                        return;
                    }

                    if (string.IsNullOrWhiteSpace(cs.文件名后缀))
                    {
                        Log.Writter("生成文件后缀为空,不能生成文件.");
                        return;
                    }

                    cs.attachMentFilename = $"{Dir.GetCurrentDirectory()}\\exceltmp\\{cs.附件文件名.ToString()}{DateTime.Now.ToString(cs.文件名后缀)}.pdf";

                    if (File.Exists(cs.attachMentFilename)) File.Delete(cs.attachMentFilename);

                    Report r = new Report();
                    r.Load(templateFilename);

                    r.RegisterData(ds.Tables[0], "Table");
                    //r.RegisterData(ds);

                    r.Prepare();

                    PDFExport pdf = new PDFExport();
                    r.Export(pdf, cs.attachMentFilename);

                    if (!File.Exists(cs.attachMentFilename))
                    {
                        Log.Writter($"附件文件不存在{cs.attachMentFilename}");
                        return;
                    }

                    DbConn.CronHistoryRecord(conn, args[0], cs.attachMentFilename.ToString());
                }
                else
                {
                    cs.attachMentFilename = DbConn.GetCronHistoryRecord(conn, args[0], cmd.HistoryRedordId);
                    Log.Writter(string.Format("历史记录附件名 {0}", cs.attachMentFilename));
                    if (cs.attachMentFilename == null) return;
                }

                if (cmd.NoSendMail)
                {
                    Log.Writter("有带不发送邮件的参数,此次执行不发邮件");
                    return;
                }

                if (cs.cmd.SendTestMail) cs.TestSendMailSet();

                Email email = new Email(cs);
                if (email.Send())
                {
                    if (cs.邮件发送失败重试)
                    {
                        string SendRetryFilename = $"{ Dir.GetCurrentDirectory()}\\SendRetry\\{args[0]}.txt";
                        if (File.Exists(SendRetryFilename)) File.Delete(SendRetryFilename);
                        Log.Writter("删除文件" + SendRetryFilename);
                    }
                    Log.Writter("邮件发送完成");
                }
                else
                {
                    if (cs.邮件发送失败重试) CronCommon.RetrySendMailRecord.CronIdRedord(cs);
                }

                conn.Close();
                conn.Dispose();
                Log.Writter("关闭数据连接");
                Log.Writter("====================================================================================");



            }
            catch (Exception ex)
            {
                Log.Writter("错误信息:" + ex.Message);
            }

        }
    }

}
